/**外包企业门户网站,生成时间:2017-04-19 09:55:35**/
package com.xbdun.service.bmp.service.system.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.xbdun.common.api.Client;
import com.xbdun.common.enums.PkGenerateEnum;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.common.page.Pager;
import com.xbdun.common.util.PkGenerator;
import com.xbdun.dao.bmp.dto.DepartNodeDto;
import com.xbdun.dao.bmp.entity.XbdunDepartDo;
import com.xbdun.dao.bmp.mapper.DepartMapper;
import com.xbdun.dao.bmp.mapper.OrleDepartMapper;
import com.xbdun.facade.bmp.exceptions.BmpBizException;
import com.xbdun.facade.bmp.request.system.DepartRequest;
import com.xbdun.facade.bmp.response.system.TreeNodeResponse;
import com.xbdun.service.bmp.biz.OrgUserBiz;
import com.xbdun.service.bmp.service.system.DepartService;

import lombok.extern.slf4j.Slf4j;


/**
 * 部门
 * @ClassName XbdunDepartServiceImpl
 * @author zhanggt
 * @2017-04-19 09:55:35
 */
@Service
@Slf4j
public class DepartServiceImpl implements DepartService {
	@Autowired
	private DepartMapper departMapper;
	@Autowired
	private OrleDepartMapper orleDepartMapper;
	@Autowired
	OrgUserBiz orgUserBiz;
	@Transactional
	public Long addXbdunDepart(DepartRequest request, Client client)throws Exception{
		XbdunDepartDo xbdunDepartDo = new XbdunDepartDo();
		BeanUtils.copyProperties(xbdunDepartDo, request);
		
		xbdunDepartDo.setOrgCode(client.getOrgCode());
		xbdunDepartDo.setOptionUser(client.getUserName());
		xbdunDepartDo.setId(PkGenerator.generateLongPk(PkGenerateEnum.SYSFRAME));
		
		departMapper.addXbdunDepart(xbdunDepartDo);
		long code = departMapper.selectToCode(xbdunDepartDo.getId());
		if(0==departMapper.updateDepartSort(xbdunDepartDo.getId(),code)){
			throw BizException.DB_INSERT_RESULT_0;
		}
		return xbdunDepartDo.getId();
	}
	
	/**
	 *删除部门，必须是在该部门下不能在存在角色情况下才能够安全删除
	 *@param id 部门Code编号
	 *@param client 客户端
	 */
	@Transactional
	public void delDepartByCode(Long id,Client client)throws Exception{
		XbdunDepartDo xbdunDepartByCode = departMapper.getXbdunDepartByCode(id,client.getOrgCode());
		if(null==xbdunDepartByCode){
			throw BmpBizException.DATA_EMPTY.newInstance("不存在机构部门");
		}
		int cnt = orleDepartMapper.existDepartRoles(id, client.getOrgCode());
		if(0!=cnt){
			throw BmpBizException.DATA_EXIST.newInstance("删除失败，原因是机构部门下还存在角色["+cnt+"]");
		}
		
		if(0==departMapper.delDepartByCode(id,client.getOrgCode(),xbdunDepartByCode.getVersion())){
			throw BmpBizException.DB_UPDATE_RESULT_0.newInstance("删除失败，平台部门不能删除");
		}
	}
	
	/**
	 * 判断是否存在,不为null则是存在
	 * @param id 主键id
	 * @return Long
	 */
	public boolean existById(long id)throws Exception{
		Assert.isTrue(id>0,"参数id必须大于零");
		Map<String,Object> param = new HashMap<String, Object>();
		
		//根据主键
		param.put("id",id);
		
		Long rlt = departMapper.existXbdunDepart(param);

		param.clear();
		param = null;

		return (null==rlt||rlt.longValue()==0?false:true);
	}
	
	/**
	 * 更新对象属性
	 * @param XbdunDepartDo	更新对象
	 * @param id
	 */
	@Transactional
	public void updateById(DepartRequest request, Client client)throws Exception{
		long xbdunOrgCode = orgUserBiz.getXbdunOrgCode();
		XbdunDepartDo xbdunDepartByCode = departMapper.getXbdunDepartByCode(request.getCode(),(client.getOrgCode()==xbdunOrgCode?xbdunOrgCode:client.getOrgCode()));
		if(null == xbdunDepartByCode){
			throw BmpBizException.DB_SELECTONE_IS_NULL;
		}
		Map<String,Object> param = new HashMap<String,Object>();
		if(StringUtils.isNotBlank(request.getDepartName())){
			 param.put("departName", request.getDepartName());
		}
		if(StringUtils.isNotBlank(request.getRemark())){
			 param.put("remark", request.getRemark());
		}
		param.put("optionUser",client.getUserName());
		
		//检索
		Map<String,Object> where = new HashMap<String,Object>();
		where.put("code", request.getCode());
		where.put("version", xbdunDepartByCode.getVersion());
		//如果不为平台机构
		if(client.getOrgCode()!=xbdunOrgCode){
			where.put("orgCode",client.getOrgCode());
		}
		if(0==departMapper.updateDynXbdunDepart(param, where)){
			param.clear();
			where.clear();
			param = null;
			where = null;
			throw BmpBizException.DB_UPDATE_RESULT_0.newInstance("部门更新失败");
		}

		param.clear();
		where.clear();
		param = null;
		where = null;
	}
	
	/**
	 * 查询分页
	 * @param where			约束条件,键是对象属性其中条件都为and连接
	 * @param orderBy		排序条件
	 * @param pageNum   	当前索引页
	 * @param numPerPage	每页显示条数
	 * @return
	 * @throws Exception
	 */
	public Pager<XbdunDepartDo> queryPager(Map<String,Object> where,String orderBy,int pageIndex,int pageSize){
		//分页对象
		Pager<XbdunDepartDo> resultPager = new Pager<XbdunDepartDo>();
		
		resultPager.setPageSize(pageSize);
		resultPager.setPageIndex(pageIndex);
		resultPager.setSort(orderBy);
		Long resultCnt = departMapper.queryPagerCount(where);
		if(null!=resultCnt&&resultCnt.longValue()==0){
			
			resultPager.setTotalCount(0);
			return resultPager;
		}
		
		//获取查询结果集List
		List<XbdunDepartDo> list = departMapper.queryPager(where, orderBy,(resultPager.getPageIndex()-1)*resultPager.getPageSize(), resultPager.getPageSize());
		
		//设置查询条数
		resultPager.setTotalCount(resultCnt.longValue());
		resultPager.setPager();
		resultPager.setData(list);
		
		return resultPager;
	}

	public List<TreeNodeResponse> queryTreeDepart(long orgCode)throws Exception{
		List<TreeNodeResponse>  result  = null;
		long xbdunOrgCode = orgUserBiz.getXbdunOrgCode();
		List<DepartNodeDto> list =  departMapper.queryTreeDepart(orgCode,xbdunOrgCode);
		if(!CollectionUtils.isEmpty(list)){
			result = new ArrayList<TreeNodeResponse>();
			TreeNodeResponse infoRes = null;
			try{
				for(DepartNodeDto info : list){
					infoRes = new TreeNodeResponse();
					infoRes.setId(info.getId());
					infoRes.setPId(StringUtils.defaultIfBlank(info.getPId(),"0"));
					infoRes.setName(info.getName());
					infoRes.setTitle(info.getTitle());
					infoRes.setBlDel(orgCode==xbdunOrgCode);//是否归属于自己机构可以删除
					result.add(infoRes);
				}
				infoRes = new TreeNodeResponse();
				//创建根目录
				infoRes.setId("0");
				infoRes.setPId("00");
				infoRes.setName("根目录");
				infoRes.setTitle("根目录");
				infoRes.setBlDel(orgCode==xbdunOrgCode);//是否归属于自己机构可以删除
				result.add(infoRes);
			}catch(Exception e){
				log.error("查询部门转换失败",e);
			}finally{
				list.clear();
				list = null;	
			}
			
		}
		return result;
	}
}